package com.wq.concurrency.aqs;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: wangqiang20995
 * @Date:2019/2/15
 * @Description:
 * @Resource:
 */
public class ReentrantReadWriteLockDemo {


    public static void main(String args[]){

        System.out.println(Integer.toBinaryString(-60));
        System.out.println(Integer.toBinaryString(60));

        System.out.println(-60 >>> 2);

        System.out.println(-60 >> 2);

        ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

        downGradeWriteLock(readWriteLock);

//        upgradeReadLock(readWriteLock);

//        orderLock(readWriteLock);
    }

    private static void downGradeWriteLock(ReadWriteLock readWriteLock){
        readWriteLock.writeLock().lock();

        System.out.println("get write lock");

        System.out.println("and ready get read lock");

        readWriteLock.readLock().lock();

        System.out.println("get read lock");

        readWriteLock.readLock().unlock();

        System.out.println("release read lock");

        readWriteLock.writeLock().unlock();

        System.out.println("release write lock");
    }

    private static void upgradeReadLock(ReadWriteLock readWriteLock){
        readWriteLock.readLock().lock();

        System.out.println("get read lock");

        System.out.println("and ready get write lock");

        readWriteLock.writeLock().lock();

        System.out.println("get write lock");

        readWriteLock.writeLock().unlock();

        System.out.println("release write lock");

        readWriteLock.readLock().unlock();

        System.out.println("release read lock");
    }

    /**
     *
     * @Author:wangqiang20995
     * @Datetime:2019/2/15 14:17
     * @param: [readWriteLock]
     * @Description:读写锁简单使用
     *
     **/
    private static void orderLock(ReadWriteLock readWriteLock) {

        readWriteLock.readLock().lock();

        System.out.println("read lock");

        readWriteLock.readLock().unlock();

        System.out.println("read unlock");

        readWriteLock.writeLock().lock();

        System.out.println("write lock");

        readWriteLock.writeLock().unlock();

        System.out.println("write unlock");
    }
}
